<?php

/**
 * collection actions.
 *
 * @package    travide
 * @subpackage collection
 * @author     Travide Project Group
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class collectionActions extends sfActions {

    public function executeShow(sfWebRequest $request) {

        $this->collection_item = Doctrine::getTable('CollectionItem')->find(array($request->getParameter('uin')));
        $this->forward404Unless($this->collection_item);
    }

    public function addSecurityRelationsToNewItem(CollectionItem $newCollectionItem = null) {
        if (sfConfig::get('app_features_enable_add_owner_relation') && sfConfig::get('app_security_owner_profile_relation_type')) {
            if ($newCollectionItem == null) {
                $newCollectionItem = new CollectionItem();
            }


            foreach ($this->getUser()->getDefaultProfileUins() as $profileUin) {
                $newRelation = new CollectionRelation;
                $relationType = Doctrine::getTable('RelationType')->getOneByIdentifier(sfConfig::get('app_security_owner_profile_relation_type'));
                if ($relationType != null) {
                    $newRelation->setRelationType($relationType);
                    $newRelation->setRelatedItemUin($profileUin);
                    $newRelation->setThisItem($newCollectionItem);

                    $newCollectionItem->getCollectionRelations()->add($newRelation);
                }
                //$this->getEmbeddedForm('NewCollectionRelation')->embedForm('sdf343', new CollectionRelationForm() );
            }
        }

        return $newCollectionItem;
    }

    public function executeNew(sfWebRequest $request) {
        /**
         * Security managed by security.yml
         */
        $this->form = new CollectionItemForm($this->addSecurityRelationsToNewItem());
    }

    public function executeCreate(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));
        /**
         * Security managed by security.yml
         */
        $this->form = new CollectionItemForm($this->addSecurityRelationsToNewItem());

        $collection_item = $this->processForm($request, $this->form);

        if ($collection_item != null) {
            if ($request->getParameter('saveAndNew')) {
                $this->redirect('CollectionNew');
            } else {
                $this->redirect('CollectionEdit', array('uin' => $collection_item->getUin()));
            }
        } else {

            $this->setTemplate('edit');
        }

        $this->setTemplate('new');
    }

    public function executeEdit(sfWebRequest $request) {
        $this->forward404Unless($collection_item = Doctrine::getTable('CollectionItem')->find(array($request->getParameter('uin'))), sprintf('Object collection_item does not exist (%s).', $request->getParameter('uin')));
        //If the user doesn't have the edit-any-collection permission then check if they own the object first
        if (!$this->getUser()->hasCredential('edit-any-collection')) {
            $this->forwardUnless($collection_item->checkIsOwner($this->getUser()->getProfileUin()), 'sfGuardAuth', 'secure');
        }

        $this->form = new CollectionItemForm($collection_item);
    }

    public function executeUpdate(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($collection_item = Doctrine::getTable('CollectionItem')->find(array($request->getParameter('uin'))), sprintf('Object collection_item does not exist (%s).', $request->getParameter('uin')));
        //If the user doesn't have the edit-any-collection permission then check if they own the object first
        if (!$this->getUser()->hasCredential('edit-any-collection')) {
            $this->forwardUnless($collection_item->checkIsOwner($this->getUser()->getProfileUin()), 'sfGuardAuth', 'secure');
        }

        $this->form = new CollectionItemForm($collection_item);

        $collection_item = $this->processForm($request, $this->form);
        if ($collection_item != null) {
            if ($request->getParameter('save')) {
                $this->redirect('CollectionShow', array('uin' => $collection_item->getUin()));
            } else {
                $this->redirect('CollectionEdit', array('uin' => $collection_item->getUin()));
            }
        } else {

            $this->setTemplate('edit');
        }
    }

    public function executeDelete(sfWebRequest $request) {
        /**
         * Disable CSRF protection for this temporarily while we sort out
         * how to let users delete from the interface with this on
         * TODO: replace this.
         */
        //$request->checkCSRFProtection();

        $this->forward404Unless($collection_item = Doctrine::getTable('CollectionItem')->find(array($request->getParameter('uin'))), sprintf('Object collection_item does not exist (%s).', $request->getParameter('uin')));

        //If the user doesn't have the delete-any-collection permission then check if they own the object first
        if (!$this->getUser()->hasCredential('delete-any-collection')) {
            $this->forwardUnless($collection_item->checkIsOwner($this->getUser()->getProfileUin()), 'sfGuardAuth', 'secure');
        }
        $collection_item->archive();

        $this->redirect('CollectionShow', array('uin' => $collection_item->getUin()));
    }

    public function executeRestore(sfWebRequest $request) {
        $this->forward404Unless($collection_item = Doctrine::getTable('CollectionItem')->find(array($request->getParameter('uin'))), sprintf('Object collection_item does not exist (%s).', $request->getParameter('uin')));
        //Check if use has permission to restore collections

        $collection_item->restore();

        $this->redirect('CollectionShow', array('uin' => $collection_item->getUin()));
    }

    public function executeSearchTags(sfWebRequest $request) {
        $tagNamePart = $request->getParameter('term');
        $tags = Doctrine::getTable('SubjectTag')->getTagsByPartNameQuery($tagNamePart)->execute();
        // if ($request->getRequestFormat() == 'ac') {
        $this->setLayout(false);
        $this->getResponse()->setContentType('text');
        // }
        $searchResults = array();
        foreach ($tags as $tag) {
            $searchResults[] = array('value' => (String) $tag);
        }

        return $this->renderText(json_encode($searchResults));
    }

    public function executeSearchCollByName(sfWebRequest $request) {
        $collNamePart = $request->getParameter('term');
        $collections = Doctrine::getTable('CollectionItem')->getCollectionsByNamePartQuery($collNamePart)->execute();
        // if ($request->getRequestFormat() == 'ac') {
        $this->setLayout(false);
        $this->getResponse()->setContentType('text');
        $searchResults = array();
        foreach ($collections as $collection) {
            $searchResults[] = array('value' => $collection->getUin(), 'label' => $collection->getCollectionName());
        }

        return $this->renderText(json_encode($searchResults));

        //}
    }

    protected function processForm(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $collection_item = $form->save();
            return $collection_item;

            //$this->redirect('collection/edit?uin='.$collection_item->getUin());
        }
    }

}
